
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.*;

import org.kxml2.io.KXmlParser;
import org.kxml2.io.KXmlSerializer;
import org.xmlpull.v1.XmlPullParser;

import com.lxb.stock.*;

public class GpTicker extends JFrame implements ActionListener
{
	public final static int FRAME_HEIGHT = 60;
	public final static int PAGE_SIZE = 8;
	static int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
	Timer timer;
	JLabel[] codeLabels;
	JLabel[] priceLabels;
	JLabel[] percentLabels;
	JPanel labelPanel;
	JLabel timeLabel;
	GpInput gpInput;
	StockList stockList;
	GStockService stockService;
	StockStorage stockStorage;
	
	public static void main(String[] args)
	{
	   JFrame frm = new GpTicker();
	   frm.setBounds(screenWidth - 200, 0, 200, 200);
	   frm.setDefaultCloseOperation(EXIT_ON_CLOSE);
	   frm.setAlwaysOnTop(true);
	   frm.pack();
	   frm.setVisible(true);
	}
	
	public GpTicker()
	{
		stockStorage = new StockStorage();
		gpInput = new GpInput(this, stockStorage.restoreStockList());
		stockList = new StockList(PAGE_SIZE);
		stockService = new GStockService();
		addWindowListener(new WindowActioner());
		
		JPanel p = new JPanel();
		
		timeLabel = new JLabel("");
		timeLabel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		p.add(timeLabel, BorderLayout.WEST);
		
		JButton addButton = new JButton("add");
		p.add(addButton, BorderLayout.EAST);
		addButton.addActionListener(this);
		add(p, BorderLayout.SOUTH);
		
		JPanel labelPanel  = new JPanel();
		labelPanel.setBackground(Color.black);
		labelPanel.setLayout(new GridLayout(8, 1, 10, 0));
		codeLabels = new JLabel[PAGE_SIZE];
		priceLabels = new JLabel[PAGE_SIZE];
		percentLabels = new JLabel[PAGE_SIZE];
		for (int i = 0; i < codeLabels.length; i ++)
		{
			codeLabels[i] = new JLabel("               ");  
			codeLabels[i].setForeground(Color.BLUE);
			labelPanel.add(codeLabels[i]);
			priceLabels[i] = new JLabel("");
			labelPanel.add(priceLabels[i]);
			percentLabels[i] = new JLabel("");
			labelPanel.add(percentLabels[i]);
		}
		add(labelPanel, BorderLayout.NORTH);
		
		
	    timer = new Timer(5000, new ActionListener() {
	        public void actionPerformed(ActionEvent e)
	        {
	          update();
	        }
	      });
	      timer.setInitialDelay(0);
	     timer.start();
		
	}
	
	public void actionPerformed(ActionEvent e)
	{
		if (e.getActionCommand() == "add")
		{
			gpInput.setBounds(this.getX() - 250, this.getY(), 
					250, 250);
			gpInput.setVisible(true);
		}
	}
	

	public void update()
	{
		String[] strs = stockList.getNextPage();
		
		if (strs == null)
		{
			for (int i = 0; i < PAGE_SIZE; i ++)
			{
				codeLabels[i].setText("               ");
				priceLabels[i].setText("");
				percentLabels[i].setText("");
			}
			return;
		}
		//System.out.println(strs[0]);
		int i = 0;
		for (; i < strs.length; i ++)
		{
			GStockInfo gsi = stockService.queryStock(strs[i]);
			if (gsi == null)
				continue;
			float f = Float.parseFloat(gsi.getC());
			Color c = Color.RED;
			if (f == 0)
				c = Color.WHITE;
			else if (f < 0)
				c = Color.GREEN;
			codeLabels[i].setForeground(c);
			priceLabels[i].setForeground(c);
			percentLabels[i].setForeground(c);
			
			codeLabels[i].setText(strs[i]);
			priceLabels[i].setText(gsi.getPrice());
			percentLabels[i].setText(gsi.getCP() + "%");
			timeLabel.setText(gsi.getTradeTime());
		}
		for (; i < PAGE_SIZE; i ++)
		{
			codeLabels[i].setText("");
			priceLabels[i].setText("");
			percentLabels[i].setText("");

		}
		
		
	}
	
	class StockList
	{
		int pageSize;
		int pageCount;
		public StockList(int pageSize)
		{
			this.pageSize = pageSize;
			this.pageCount = 0;
		}
		public String[] getAllStocks()
		{
			Object[] os = gpInput.getList();
			if ((os == null)
				|| (os.length == 0))
				return null;
			Vector strings = new Vector();
			for (int i = 0; i < os.length; i ++)
				strings.add((String)os[i]);
			return (String[])strings.toArray(new String[0]);
		}
		
		public String[] getNextPage()
		{
			Object[] os = gpInput.getList();
			if ((os == null)
				|| (os.length == 0))
				return null;
			int temp = pageCount + 1;
			if ((temp + 1) * pageSize > os.length)
				pageCount = 0;
			else 
				pageCount = temp + 1;
			Vector strings = new Vector();
			int pageStart = pageCount * pageSize;
			for (int i = pageStart; i < os.length && i < (pageStart + pageSize); i ++)
				strings.add(os[i]);
			
			return (String[])strings.toArray(new String[0]);
				
		}
		
	}
	
	class WindowActioner extends WindowAdapter
	{
		public void windowClosing(WindowEvent e)
		{
			stockStorage.storeStockList(stockList.getAllStocks());
		}
	}
	
	class StockStorage
	{
		private final static String TAG_STOCKS = "stocks";
		private final static String TAG_STOCK = "stock";
		private final static String ATTR_ID = "id";
		
		String storageFileName = "." + File.separator + "stocks.xml";
		
		public void storeStockList(String[] stocks)
		{
			if (stocks == null)
				return;
			File file = new File(storageFileName);
			if (file.exists())
				file.delete();
			try
			{
				FileOutputStream fos = new FileOutputStream(file);
				KXmlSerializer serializer = new KXmlSerializer();
				serializer.setOutput(fos, null);
				serializer.startDocument(null, null);
				
				serializer.startTag(null, TAG_STOCKS);
				
				for (int i = 0; i < stocks.length; i ++)
				{
					serializer.startTag(null, TAG_STOCK);
					serializer.attribute(null, ATTR_ID, stocks[i]);
					serializer.endTag(null, TAG_STOCK);
				}
				
				serializer.endTag(null, TAG_STOCKS);
				serializer.endDocument();
				
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}

		}
		
		public String[] restoreStockList()
		{
			File file = new File(storageFileName);
			if (!file.exists())
				return null;
			System.out.println(file.getAbsolutePath());
			Vector stockList = new Vector();
			try
			{
				FileInputStream fis = new FileInputStream(file);
				KXmlParser parser = new KXmlParser();
				parser.setInput(fis, null);
				parser.require(KXmlParser.START_DOCUMENT, null, null);
				parser.next();
				parser.require(KXmlParser.START_TAG, null, TAG_STOCKS);
				while (parser.nextTag() == KXmlParser.START_TAG)
				{
					String name = parser.getName();
					if (name.equals(TAG_STOCK))
					{
						String id = parser.getAttributeValue(null, ATTR_ID);
						stockList.add(id);
						parser.next();
					}
					parser.require(KXmlParser.END_TAG, null, name);
				}
				parser.require(KXmlParser.END_TAG, null, TAG_STOCKS);
				parser.next();
				parser.require(XmlPullParser.END_DOCUMENT, null, null);

			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			return (String[])stockList.toArray(new String[0]);

		}
		
	}

	 
	 
 
}
